#include <stdlib.h>
#include "typedef.h"
#include "common.h"
#include "package.h"
#include "task.h"
#include "taskctrl.h"
#include "os.h"

static PTASKINFO watcher = NULL;

void taskctrl_init()
{
	tsk_init();
}

int taskctrl_watch(PTASKWATCHINFO info, int flag)
{
	int ret = WATCH_RET_END;

	if (!info)
		return WATCH_RET_ERROR;

	if (flag == WATCH_FLG_NEW)
	{
		watcher = tsk_getlist();
	}

	if (!watcher)
		return ret;

	while(watcher)
	{
		if (watcher->status == TASK_STAT_END)
		{
			info->type = WATCH_TYPE_END;
			info->taskId = watcher->taskId;
			info->flag = 0;

			ret = WATCH_RET_NOEND;

			tsk_remove ( watcher->taskId );
		}
		else
		{
			/* Do nothing */
		}

		watcher = watcher->next;

		if (ret == WATCH_RET_NOEND)
		{
			break;
		}
	}

	return ret;
}

void taskctrl_update()
{
	PTASKINFO header = tsk_getlist();
	if (!header)
		return;

	PTASKINFO tmp = header;
	while(tmp)
	{
		if (tmp->status == TASK_STAT_RUNNING
				&& !os_isrunning(tmp->pid))
		{
			tmp->status = TASK_STAT_END;
		}

		tmp = tmp->next;
	}
}

int taskctrl_run(int taskId, char* command)
{
	int pid = os_run(command);
	if (pid == -1)
		return ERROR;

	tsk_add(taskId, pid, command);

	return SUCCESS;
}

void taskctrl_release()
{
	tsk_release();
}
